<template>
  <a-spin class="productList" tip="加载中..." :spinning="isLoading">
    <!-- 主体部分 -->
    <div class="main-body merchant-body">
      <div class="explain-header">
        <div class="explain-main">
          <p class="explain-title">产品指标说明</p>
          <transition name="mybox">
            <div v-show="explainShow" class="explain-box">
              <div class="explain-item">
                <p><span>转发量：</span>该产品被分享的次数</p>
                <p><span>浏览量：</span>该产品被浏览的次数</p>
              </div>
              <div class="explain-item">
                <p><span>实际销量：</span>该套餐的销售数量</p>
                <p><span>订单流水：</span>该套餐销售的订单对应的支付金额</p>
                <p><span>核销数量：</span>该套餐的核销数量</p>
                <p><span>核销流水：</span>该套餐核销订单对应的支付金额</p>
                <p><span>核销率：</span>核销数量/实际销量 </p>
              </div>
              <div class="explain-item">
                <p><span>退款数量：</span>该套餐退款的数量</p>
                <p><span>退款金额：</span>该套餐退款的订单对应的支付金额</p>
                <p><span>退款率：</span>退款数量/实际销量</p>
              </div>
            </div>
          </transition>
          <a-button class="explain-btn" type="link" @click="togglebox(true)">
            {{ explainShow ? '收起详情' : '展开详情' }}
            <a-icon type="up" :style="{ fontSize: '12px', color: '#1D6FE9' }" v-if="explainShow"/>
            <a-icon type="down" :style="{ fontSize: '12px', color: '#1D6FE9' }" v-else/>
          </a-button>
        </div>
      </div>
      <div class="filter-search">
        <div class="search">
          <span class="search-name">产品名称：</span>
          <a-input
              placeholder="请输入"
              class="filter-input"
              v-model="search.productName"
              @pressEnter="handleSearch"
          />
          <span class="search-name">套餐名称：</span>
          <a-input
              placeholder="请输入"
              class="filter-input"
              v-model="search.productItemName"
              @pressEnter="handleSearch"
          />
          <span class="search-name">状态：</span>
          <a-select placeholder="请选择" class="filter-input" :options="productStatus" allowClear  v-model="search.productStatus" @change="handleSearch">
          </a-select>
          <span class="search-name">上架渠道：</span>
          <a-select placeholder="请选择" class="filter-input" allowClear :options="channelList"  v-model="search.saleChannels" @change="handleSearch">
          </a-select>
          <span class="search-name">产品类别：</span>
          <a-select placeholder="请选择" style="width: 300px" allowClear class="filter-input" :options="productCategoryList"  v-model="search.productCategory" @change="handleSearch">
          </a-select>
          <span class="search-name">售卖时间：</span>
          <a-range-picker separator="至"  :placeholder="['开始时间', '结束时间']" v-model="saleTime" @change="onSelectSaleDateChange"/>
          <span class="search-name">使用时间：</span>
          <a-range-picker separator="至"  :placeholder="['开始时间', '结束时间']" v-model="useTime" @change="onSelectUseDateChange"/>
          <a-button class="search-btn" type="primary" @click="handleSearch">查询</a-button>
          <a-button @click="clearSearch">重置</a-button>
        </div>
      </div>
      <a-table
          :dataSource="tableList"
          :columns="tableColumns"
          :pagination="false"
          :scroll="{ x: 500, y: tableHeight }"
          :rowKey="(record, index) => index"
          tableLayout="fixed"
      >
        <template slot="productName" slot-scope="text, record">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{record.productName}}（{{record.productId}}）</span>
            </template>
            {{record.productName}}（{{record.productId}}）
          </a-tooltip>
        </template>
        <template slot="productItemName" slot-scope="text, record">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{record.productItemName}}（{{record.productItemId}}）</span>
            </template>
            {{record.productItemName}}（{{record.productItemId}}）
          </a-tooltip>
        </template>
        <template slot="productCategory" slot-scope="text, record">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{record.productCategory}}</span>
            </template>
            {{record.productCategory}}
          </a-tooltip>
        </template>
        <template slot="saleTime" slot-scope="text, record">
          <span v-if="record.saleStartTime">{{record.saleStartTime | dateFormat('YYYY-MM-DD')}}</span>
          <span v-else>/ </span>
          -
          <span v-if="record.saleEndTime">{{record.saleEndTime | dateFormat('YYYY-MM-DD')}}</span>
          <span v-else> /</span>
        </template>
        <template slot="useTime" slot-scope="text, record">
          <span v-if="record.useStartTime">{{record.useStartTime | dateFormat('YYYY-MM-DD')}}</span>
          <span v-else>/ </span>
          -
          <span v-if="record.useEndTime">{{record.useEndTime | dateFormat('YYYY-MM-DD')}}</span>
          <span v-else> /</span>
        </template>
        <template slot="allOrderMoney" slot-scope="text, record">
          {{price(record.allOrderMoney)}}
        </template>
        <template slot="allCompleteOrderMoney" slot-scope="text, record">
          {{price(record.allCompleteOrderMoney)}}
        </template>
        <template slot="allRefundOrderMoney" slot-scope="text, record">
          {{price(record.allRefundOrderMoney)}}
        </template>
        <template slot="completeRate" slot-scope="text, record">
          {{formatDecimal(record.completeRate*100,2)}}%
        </template>
        <template slot="refundRate" slot-scope="text, record">
          {{formatDecimal(record.refundRate*100,2)}}%
        </template>
        <template slot="action" slot-scope="text, record">
          <span class="action" @click="getLocationDetail(record)">查看</span>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
          v-model="search.pageNum"
          showQuickJumper
          showLessItems
          :showTotal="(total) => `共 ${total} 条`"
          style="margin: 10px 0;"
          :total="total"
          :pageSize="search.pageSize"
          @change="handleTablePageChange"
      />
    </div>
    <a-modal
        title="站点明细"
        :visible="detailVisible"
        @cancel="cancelBlock"
        :width="width"
    >
      <p class="product-title">{{thisProductName}}</p>
      <div class="explain-header">
        <div class="explain-main">
          <p class="explain-title">站点指标说明</p>
          <transition name="mybox">
            <div v-show="explainShowSub" class="explain-box">
              <div class="explain-item">
                <p><span>订单量/核销量/退款量：</span>该站点销售/核销/退款的套餐数量</p>
                <p><span>占比：</span>该站点的订单量/核销量/退款量在所有站点中所占的比例</p>
              </div>
              <div class="explain-item">
                <p><span>订单流水/核销流水/退款流水：</span>该站点销售/核销/退款的订单对应的支付金额</p>
                <p><span>占比：</span>该站点的订单流水/核销流水/退款流水在所有站点中所占的比例</p>
              </div>
            </div>
          </transition>
          <a-button class="explain-btn" type="link" @click="togglebox(false)">
            {{ explainShowSub ? '收起详情' : '展开详情' }}
            <a-icon type="up" :style="{ fontSize: '12px', color: '#1D6FE9' }" v-if="explainShowSub"/>
            <a-icon type="down" :style="{ fontSize: '12px', color: '#1D6FE9' }" v-else/>
          </a-button>
        </div>
      </div>
      <a-table :columns="detailTableColumns" :scroll="{ x: 500, y: tableHeight }" :data-source="tableDetailList" :pagination="false" size="middle" rowKey="id" tableLayout="fixed" :loading="isDetailLoading" >
        <template slot="allOrderNum" slot-scope="text, record">
          {{record.allOrderNum}}（{{record.allOrderNumRatio}}）
        </template>
        <template slot="allOrderMoney" slot-scope="text, record">
          {{price(record.allOrderMoney)}}（{{record.allOrderMoneyRatio}}）
        </template>
        <template slot="allCompleteOrderNum" slot-scope="text, record">
          {{record.allCompleteOrderNum}}（{{record.allCompleteOrderNumRatio}}）
        </template>
        <template slot="allCompleteOrderMoney" slot-scope="text, record">
          {{price(record.allCompleteOrderMoney)}}（{{record.allCompleteOrderMoneyRatio}}）
        </template>
        <template slot="allRefundOrderNum" slot-scope="text, record">
          {{record.allRefundOrderNum}}（{{record.allRefundOrderNumRatio}}）
        </template>
        <template slot="allRefundOrderMoney" slot-scope="text, record">
          {{price(record.allRefundOrderMoney)}}（{{record.allRefundOrderMoneyRatio}}）
        </template>
      </a-table>
      <template slot="footer">
        <div class="page">
          <a-pagination :current="detailPagination.pageNum" style="margin: 10px 0;" :total="detailTotal" :pageSize="detailPagination.pageSize" showLessItems @change="handleDetailTableChange" />
        </div>
      </template>
    </a-modal>
  </a-spin>
</template>

<script>
import {
  getAllBusinessCategory,
  lastDay,
  getProductDetail,
  getProductDetailSale,
  getAllProductCategory,
} from "@/service";
import { dateFormat } from 'nearby-common'
import moment from "moment";
export default {
  name: 'productList',
  data() {
    return {
      isLoading: false,
      isDetailLoading: false,
      total: 0,
      search:{
        pageNum: 1,
        pageSize: 10,
        day:"",
        businessId:undefined,
        productName:undefined,
        productItemName:undefined,
        saleChannels:undefined,
        saleStartTime:undefined,
        saleEndTime:undefined,
        useStartTime:undefined,
        useEndTime:undefined,
        productStatus:undefined,
        productCategory:undefined,
      },
      tableList:[],
      productCategoryList:[],
      productStatus:[
        {label:"已下架",value:7},
        {label:"在售",value:6},
        {label:"跟进",value:5},
      ],
      channelList:[
        {label:"微信",value:"微信"},
        {label:"抖音",value:"抖音"},
        {label:"支付宝",value:"支付宝"},
      ],
      saleTime: [null, null],
      useTime: [null, null],
      tableDetailList:[],
      detailTotal:0,
      detailVisible:false,
      detailPagination:{
        pageNum: 1,
        pageSize: 10,
      },
      detailTableData:[],
      width:'85%',
      detailInfo:{},
      thisProductName: '',
      explainShow: true,
      explainShowSub: true
    }
  },
  filters: {
    dateFormat
  },
  computed: {
    // table 配置
    tableColumns() {
      return [
        { title: '产品名称（ID）', width: 350, dataIndex: 'productName',ellipsis: true,scopedSlots: { customRender: 'productName' } },
        { title: '套餐名称（ID）', width: 350, dataIndex: 'productItemName',ellipsis: true,scopedSlots: { customRender: 'productItemName' } },
        { title: '产品类别', width: 300, dataIndex: 'productCategory',scopedSlots: { customRender: 'productCategory' } },
        { title: '售卖日期', width: 250, dataIndex: 'saleTime',scopedSlots: { customRender: 'saleTime' } },
        { title: '使用日期', width: 250, dataIndex: 'useTime',scopedSlots: { customRender: "useTime" }},
        { title: '状态', width: 200, dataIndex: 'productStatusName'},
        { title: '上架渠道', width: 200, dataIndex: 'saleChannels'},
        { title: '转发量', width: 200, dataIndex: 'forwardNum'},
        { title: '浏览量', width: 200, dataIndex: 'browseNum'},
        { title: '实际销量', width: 200, dataIndex: 'allOrderNum'},
        { title: '订单流水', width: 200, dataIndex: 'allOrderMoney',scopedSlots: { customRender: "allOrderMoney" } },
        { title: '核销数量', width: 200, dataIndex: 'allCompleteOrderNum' },
        { title: '核销流水', width: 200, dataIndex: 'allCompleteOrderMoney',scopedSlots: { customRender: "allCompleteOrderMoney" } },
        { title: '核销率', width: 200, dataIndex: 'completeRate',scopedSlots: { customRender: "completeRate" }},
        { title: '退款数量', width: 200, dataIndex: 'allRefundOrderNum'},
        { title: '退款金额', width: 200, dataIndex: 'allRefundOrderMoney',scopedSlots: { customRender: "allRefundOrderMoney" } },
        { title: '退款率', width: 200, dataIndex: 'refundRate',scopedSlots: { customRender: "refundRate" } },
        {
          title: '站点明细',
          key: 'operation',
          fixed: 'right',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ]
    },
    detailTableColumns() {
      return [
        { title: '站点名称', width: 150, dataIndex: 'locationName',ellipsis: true },
        { title: '订单量（占比）', width: 150, dataIndex: 'allOrderNum',ellipsis: true,scopedSlots: { customRender: 'allOrderNum' } },
        { title: '订单流水（占比）', width: 150, dataIndex: 'allOrderMoney',scopedSlots: { customRender: 'allOrderMoney' }  },
        { title: '核销量（占比）', width: 150, dataIndex: 'allCompleteOrderNum',scopedSlots: { customRender: 'allCompleteOrderNum' } },
        { title: '核销流水（占比）', width: 150, dataIndex: 'allCompleteOrderMoney',scopedSlots: { customRender: "allCompleteOrderMoney" }},
        { title: '退款量（占比）', width: 150, dataIndex: 'allRefundOrderNum',scopedSlots: { customRender: 'allRefundOrderNum' } },
        { title: '退款流水（占比）', width: 150, dataIndex: 'allRefundOrderMoney',scopedSlots: { customRender: 'allRefundOrderMoney' } }
      ]
    },
  },

  methods: {
    formatDecimal(num, decimal) {
      if (isNaN(num)) return "0.00";
      num = num.toString()
      let index = num.indexOf('.')
      if (index !== -1) {
        num = num.substring(0, decimal + index + 1)
      } else {
        num = num.substring(0)
      }
      return parseFloat(num).toFixed(decimal)
    },
    price(a) {
      var num = Number(a);
      if (isNaN(num)) return "0.00";
      if (!num) {
        //等于0
        return num + ".00";
      } else {
        //不等于0
        num = Math.round(num * 100) / 10000;
        num = num.toFixed(2);
        num += ""; //转成字符串
        var reg =
            num.indexOf(".") > -1
                ? /(\d{1,3})(?=(?:\d{3})+\.)/g
                : /(\d{1,3})(?=(?:\d{3})+$)/g; //千分符的正则
        return num.replace(reg, "$1,"); //千分位格式化
      }
    },
    clearSearch(){
      this.search = {
        pageNum: 1,
        pageSize: 10,
        day:this.search.day,
        businessId:this.search.businessId,
        productName:undefined,
        productItemName:undefined,
        saleChannels:undefined,
        saleStartTime:undefined,
        useStartTime:undefined,
        productStatus:undefined,
        productCategory:undefined
      };
      this.saleTime = [null, null];
      this.useTime = [null, null];
      this.getTabTableList();
    },
    handleSearch(){
      this.search.pageNum = 1
      this.getTabTableList()
    },
    handleTablePageChange(num) {
      this.search.pageNum = num
      this.getTabTableList()
    },
    handleDetailTableChange(num){
      this.detailPagination.pageNum = num
      this.getLocationDetailList()
    },
    getLocationDetail(row){
      this.thisProductName = row.productItemName + '（' + row.productItemId + ')';
      this.isDetailLoading = true;
      this.detailInfo = row;
      this.detailPagination.pageNum = 1;
      this.getLocationDetailList();
    },
    getLocationDetailList(){
      this.isDetailLoading = true;
      this.tableDetailList = [];
      let param={
        productItemId:this.detailInfo.productItemId,
        day:this.search.day,
        ...this.detailPagination
      }
      getProductDetailSale(param).then(res=>{
        if (res.total === 0) {
          this.$messageSend.error("暂无站点明细数据");
          return;
        }
        this.tableDetailList = res.list;
        this.tableDetailList.forEach(item=>{
          item.allOrderNumRatio = this.formatDecimal(item.allOrderNum * 100 / this.detailInfo.allOrderNum, 2) + "%";
          item.allOrderMoneyRatio = this.formatDecimal(item.allOrderMoney * 100 / this.detailInfo.allOrderMoney, 2) + "%";
          item.allCompleteOrderNumRatio = this.formatDecimal(item.allCompleteOrderNum * 100 / this.detailInfo.allCompleteOrderNum, 2) + "%";
          item.allCompleteOrderMoneyRatio = this.formatDecimal(item.allCompleteOrderMoney * 100 / this.detailInfo.allCompleteOrderMoney, 2) + "%";
          item.allRefundOrderNumRatio = this.formatDecimal(item.allRefundOrderNum * 100 / this.detailInfo.allRefundOrderNum, 2) + "%";
          item.allRefundOrderMoneyRatio = this.formatDecimal(item.allRefundOrderMoney * 100 / this.detailInfo.allRefundOrderMoney, 2) + "%";
        })
        this.detailTotal = res.total;
        this.detailVisible = true;
      }).finally(() => {
        this.isDetailLoading = false
      })
    },
    onSelectUseDateChange(data, dateString) {
      this.search.useStartTime = dateString[0] ? moment(dateString[0]).format('yyyy-MM-DD 00:00:00'): undefined;
      this.search.useEndTime = dateString[1] ? moment(dateString[1]).format('yyyy-MM-DD 23:59:59'): undefined;
      this.handleSearch();
    },
    onSelectSaleDateChange(data, dateString) {
      this.search.saleStartTime = dateString[0] ? moment(dateString[0]).format('yyyy-MM-DD 00:00:00'): undefined;
      this.search.saleEndTime = dateString[1] ? moment(dateString[1]).format('yyyy-MM-DD 23:59:59'): undefined;
      this.handleSearch();
    },
    getTabTableList(){
      this.tableList = [];
      this.isLoading = true
      getProductDetail(this.search).then(res=>{
        this.tableList = res.list;
        this.total = res.total;
      }).finally(() => {
        this.isLoading = false
      })
    },
    getAllProductCategory(){
      let param = {
        businessId: this.search.businessId,
        day: this.search.day
      };
      getAllProductCategory(param).then(res=>{
        this.productCategoryList = res;
      })
    },
    cancelBlock(){
      this.detailVisible = false
      this.explainShowSub = true
    },
    togglebox(type){
      if(type){
        this.explainShow = !this.explainShow;
      }else{
        this.explainShowSub = !this.explainShowSub;
      }
    },
  },
  async created() {
    this.search.businessId = parseInt(this.$route.query.businessId);
    const time = await lastDay();
    this.search.day = time;
    await this.getAllProductCategory();
    await this.getTabTableList();
  }
}
</script>

<style scoped lang="scss">
.productList{
  height: 100%;
  background-color: #ffffff;
}
@media screen and (max-width: 1920px){
  .filter-search{
    .filter-input, .search-btn, .filter-select, .rest-btn{
      margin-top: 20px;
    }
  }
}
.filter-search {
  margin: 10px 0;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  overflow: hidden;
  background: #F5F5F5;
  border-radius: 4px;
  border: 1px solid #F0F0F0;
  padding: 10px 14px;
  .search-name{
    margin-left: 20px;
  }
  .search-name:first-child{
    margin-left: 0;
  }
  .search-btn{
    margin-left: 20px;
  }
  .filter-input {
    width: 180px;
  }
  .filter-select {
    width: 300px;
  }
  .filter-select {
    width: 140px;
  }
}
/deep/
.ant-table-thead
> tr
> th
.ant-table-column-sorter
.ant-table-column-sorter-inner-full .on {
  color: #bfbfbf !important;
}
.action{
  color: #0090FF;
  cursor: pointer;
}
/deep/ .ant-modal .ant-modal-body {
  .explain-header{
    padding-top: 0;
    margin: 10px 0;
  }
  .product-title{
    font-size: 24px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    margin: 0;
  }
}
</style>
